package com.zx._06_JVM.chapter_02_gc;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import lombok.extern.slf4j.Slf4j;

/**
 * @version v1.0
 * @Project: knowledge
 * @Title: 强软弱虚
 * @author: zhangxue
 * @date: 2020年4月24日下午3:29:28
 * @company: 未知
 * @Copyright: Copyright (c) 2015
 */
@Slf4j
public class 强软弱虚 {

    public static void main(String[] args) {
        // 1 强引用
        Object obj = new Object();
        log.info("1.强引用 gc before = {}", obj);
        System.gc();
        log.info("1.强引用 gc after = {}", obj);

        // 2. 软引用,内存不够自动进行gc的时候，会回收这个
        // 		作用：主要是用在一些缓存的临时保存
        SoftReference<Object> soft = new SoftReference<Object>(new Object());
        log.info("2.软引用 gc before = {}", soft.get());
        System.gc();
        log.info("2.软引用 gc after = {}", soft.get());

        // 3.弱引用 , 一旦发生gc对象就会被回收
        // 		作用：比如 ThreadLocal   {@link ThreadLocalDemo}
        WeakReference<Object> weak = new WeakReference<>(new Object());
        log.info("3.弱引用 gc before = {}", weak.get());
        System.gc();
        log.info("3.弱引用 gc after = {}", weak.get());

        // 4.虚引用，创建之后立刻被回收
        //    作用：管理堆外内存，进行垃圾回收。防止堆外内存造成内存泄露
        PhantomReference<Object> reference = new PhantomReference<>(new Object(), new ReferenceQueue<>());
        log.info("4.虚引用  obj = {}", reference.get());

    }

}
